package top.usts.springframework.core.io;

import cn.hutool.core.lang.Assert;
import top.usts.springframework.util.ClassUtils;

import java.io.*;

/**
 * @description:
 * @author: CJ
 * @date: 2022/2/22
 */
public class ClassPathResource implements Resource{

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "path must not be null");
        this.path = path;
        this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream resourceAsStream = classLoader.getResourceAsStream(path);
        if (resourceAsStream == null) {
            throw new FileNotFoundException(
                    this.path + " cannot be opend because it does not exist"
            );
        }
        return resourceAsStream;
    }
}
